package org.myy.learn.hot.二叉树.层序遍历;

import lombok.extern.slf4j.Slf4j;

import java.util.*;

@Slf4j
public class Solution {
    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if (root == null){return list;}

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()){
            long size = queue.size();
            List<Integer> level = new ArrayList<>();
            while (size > 0){
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null){
                    queue.offer(node.left);
                }
                if (node.right != null){
                    queue.offer(node.right);
                }
                size--;
            }
            list.add(level);
        }
        return list;
    }

    /**
     * 构建树
     * @param values
     * @return
     */
    private static TreeNode buildTree(Integer[] values){
        if (values == null || values.length == 0){return null;}

        TreeNode root = new TreeNode(values[0]);
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        int index = 1;
        while (!queue.isEmpty() && index < values.length){
            TreeNode node = queue.poll();

            //左节点
            if(index < values.length && values[index] != null){
                node.left = new TreeNode(values[index]);
                queue.offer(node.left);
            }
            index++;

            //右节点
            if(index < values.length && values[index] != null){
                node.right = new TreeNode(values[index]);
                queue.offer(node.right);
            }
            index++;

        }
        return root;
    }

    public static void main(String[] args) {
        Integer[] values = new Integer[]{3,9,20,null,null,15,7};
        TreeNode root = buildTree(values);
        List<List<Integer>> list = levelOrder(root);
        System.out.println(list);
        log.info("执行结束，层序遍历={}", list);
    }
}
